import 'package:casdon/common/service/tuya_service.dart';
import 'package:casdon/core/extentions/list_extern.dart';

import 'package:casdon/modules/recipe/data/api/recipe_product_api.dart';
import 'package:casdon/modules/recipe/domain/states/recipe_canuse_product_list_state.dart';

import 'package:casdon/modules/recipe/domain/usecase/recipe_product_list_usecase.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:tuya_home_sdk_flutter/tuya_home_sdk_flutter.dart';

// 判断云菜谱是否有可用设备

class RecipeCanUseProductsNotifier
    extends AutoDisposeFamilyNotifier<RecipeCanUseProductListState, String> {
  @override
  RecipeCanUseProductListState build(String recipeId) {
    // 初始值
    _load(recipeId);
    return RecipeCanUseProductListState.initial();
  }

  Future<void> _load(String recipeId) async {
    final productListRet = await ref
        .read(recipeProductListUsecaseProvider)
        .execute(recipeId: recipeId);

    if (productListRet.isEmpty) {
      state = RecipeCanUseProductListState.initial();
      return;
    }

    final devList = await TuyaService().homeDeviceList();

    final pairs =
        findMatchingPairs<RecipeProductApi, ThingSmartDeviceModel, String>(
          productListRet,
          devList,
          (a) => a.tuyaPid ?? "",
          (b) => b.productId,
        );
    if (pairs.isEmpty) {
      state = RecipeCanUseProductListState.initial();
      return;
    }

    final pidMap = Map.fromEntries(
      productListRet
          .where((e) => e.tuyaPid != null && e.pid != null)
          .map((e) => MapEntry(e.tuyaPid!, e.pid!)),
    );
    if (pairs.isEmpty) {
      state = RecipeCanUseProductListState.initial();
      return;
    } else {
      state = state.copyWith(
        devList: pairs.map((e) => e.$2).toList(),
        pidMap: pidMap,
      );
    }
  }
}

// Provider 声明要用 `.family`
final recipeCanUseProductsProvider = NotifierProvider.family
    .autoDispose<
      RecipeCanUseProductsNotifier,
      RecipeCanUseProductListState,
      String
    >(RecipeCanUseProductsNotifier.new);
